<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\JasminumCalendar\Controllers;

use Gotcha\App\Extensions\GotchaCulturesExtension;
use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaLogsExtension;
use Gotcha\App\Extensions\HttpExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\JasminumCalendarEvents;
use GotchaDatabase\JasminumCalendarEventsQuery;

class AdminController extends Controller {
    public function Index() {
        return parent::View();
    }

    public function Create() {
        return parent::View();
    }

    public function CreatePost() {
        $http = new HttpExtension();

        if(empty($_POST['Hall']) || empty($_POST['Date']) || !isset($_POST['Hall']) || !isset($_POST['Date'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Calendar/Create?error=1'));
            exit;
        }

        if(is_null($_POST['Description'])) {
            $_POST['Description'] = '';
        }

        // Add new content
        try {
            $event = new JasminumCalendarEvents();
            $event->setHall($_POST['Hall']);
            $event->setDate($_POST['Date']);
            $event->setDescription($_POST['Description']);
            $event->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Calendar'));
        exit;
    }

    public function Edit() {
        return parent::View();
    }

    public function EditPost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id']) || !isset($_POST['Id'])) {
            die('Error');
        }

        if(empty($_POST['Hall']) && !isset($_POST['Hall']) || empty($_POST['Date']) || !isset($_POST['Date'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Calendar/Edit?error=1&id='.$_POST['Id']));
            exit;
        }

        if(is_null($_POST['Description'])) {
            $_POST['Description'] = '';
        }

        // Update
        try {
            $event = JasminumCalendarEventsQuery::create()
                        ->findOneById($_POST['Id'])
                            ->setHall($_POST['Hall'])
                            ->setDate($_POST['Date'])
                            ->setDescription($_POST['Description'])
                                ->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Calendar'));
        exit;
    }

    public function Delete() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id']) || !isset($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Calendar?error=2'));
            exit;
        }

        // Delete element
        try {
            JasminumCalendarEventsQuery::create()->findOneById($_GET['id'])->delete();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Calendar'));
        exit;
    }

    public function returnEvents() {
        $events = JasminumCalendarEventsQuery::create()
                    ->orderById()
                        ->find();

        // HTML cache
        $html = '';
        foreach ($events as $event) {
            $hall = array_search($event->getHall(), $this->getHalls());

            $html .= '<tr>';
            $html .= sprintf('<td>%s</td><td>%s</td><td>%s</td><td>[ <a href="%s?id=%s">Edytuj</a> | <a href="%s?id=%s" class="delete">Usuń</a> ]</td>', $hall, $event->getDate(), $event->getDescription(), parent::UrlContent('/Admin/Jasminum/Calendar/Edit'), $event->getId(), parent::UrlContent('/Admin/Jasminum/Calendar/Delete'), $event->getId());
            $html .= '</tr>';
        }

        if($events->count() == 0) {
            $html .= '<tr><td colspan="4">Nie ma dodanych wydarzeń.</td></tr>';
        }

        return $html;
    }

    public function getHalls() {
        $halls = new \ReflectionClass('Modules\JasminumCalendar\Enums\Halls');
        return $halls->getConstants();
    }

    public function returnHalls() {
        $html = '';
        $html .= '<select name="Hall">';

        foreach ($this->getHalls() as $hallName => $hallId) {
            $html .= sprintf('<option value="%s">%s</option>', $hallId, $hallName);
        }

        $html .= '</select>';

        return $html;
    }

    public function returnEvent($id) {
        $event = JasminumCalendarEventsQuery::create()
                    ->findOneById($id);
        return $event;
    }
}